/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controles;

import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javassist.bytecode.stackmap.TypeData;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import modelos.Articulo;
import modelos.Resumen;
/**
 *
 * @author ChEkO_Guajardo
 */
public class subirArticuloServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> ands
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException, Exception {
            PrintWriter out = response.getWriter();    
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);            
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
              
                }
            }else {
                if (!item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    String relativeWebPath = "/WEB-INF/uploads";
                    String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
                    File uploadedFile = new File(absoluteFilePath, fileName);
                    item.write(uploadedFile);
                    //out.println(fileName);
                    //out.println(contentType);
                    //out.println(sizeInBytes);
                    //out.println(isInMemory);
                    FileInputStream fstream = new FileInputStream(uploadedFile);
                    DataInputStream in = new DataInputStream(fstream);
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));
                    String strLine;
                    String articulo="";
                    String resumen="";
                    int cont=0;
                    while ((strLine = br.readLine()) != null)   {
                        if (cont<=2){
                            resumen+=""+strLine;
                        }
                        articulo+=" "+strLine;
                        cont++;
                    } 
                    resumen+="...";
                    //out.println(articulo);
                    in.close();
                    Articulo art= new Articulo();
                    art.setExtension(cont);
                    art.setContenido(articulo);
                    String title= ""+uploadedFile;
                    art.setTitulo(title);                    
                    int idArt=art.agregar();
                    Resumen res = new Resumen();
                    res.setIdArticulo(idArt);
                    res.setContenidoResumen(resumen);
                    res.agregar();
                    String url="/jsp/pantallaPrincipal.jsp";      
                    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                    dispatcher.forward(request, response);                       
                }

             }                
            }
       
    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(subirArticuloServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(subirArticuloServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(subirArticuloServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(subirArticuloServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
